package com.ddf.publics.controller;

import com.alibaba.fastjson.JSON;
import com.ddf.publics.config.Utill;
import com.ddf.publics.entity.*;
import com.ddf.publics.service.*;
import com.ddf.publics.tool.Constant;
import com.ddf.publics.tool.MoneyFund;
import com.ddf.publics.utils.ImgValidateCodeUtil;
import com.ddf.publics.utils.RedisUtil;
import com.ddf.publics.utils.VerifyUtil;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/admin")
public class adminController {
    @Autowired
    private DebitMarkService debitMarkService;
    @Autowired
    private DebitTypeService debitTypeService;
    @Autowired
    private LoanApplicationService loanApplicationService;
    @Autowired
    private ZeroService zeroService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private  LooseBidService looseBidService;
    @Autowired
    private ClanTabService clanTabService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private FundService fundService;

    @Autowired
    private UserOrderService userOrderService;
    @RequestMapping({"/toLogin"})
    public String login(){
        return "manage_pages/login";
    }

    @RequestMapping({"/index","/"})
    public String index(Model model){
        return "manage_pages/index";
    }

    @RequestMapping("/dueEchats")
    @ResponseBody
    public List<Map> dueEchats(){
        return zeroService.loanEchars();
    }

    /**
     * @description 广告、公告管理
     * @author jose
     * @date 2020/6/17 10:33
     * @params [page, modelMap]
     * @return java.lang.String
     */
    @RequestMapping("/advert")
    public String listNotice(Page page, ModelMap modelMap) {
        page.setAllCount(noticeService.countNotice());
        page.setCount(3);
        List<Notice> notices = noticeService.listPage(page);
        modelMap.addAttribute("page", page);
        modelMap.addAttribute("obj", notices);
        return "manage_pages/advert";
    }

    @RequestMapping("/toLogin-error")
    public String toerror(Model model,HttpServletRequest request){
        if(request.getAttribute("msg")!=null){//验证码错误
            model.addAttribute("msg",request.getAttribute("msg"));
        }else {//账号密码错误
            model.addAttribute("msg","账号或密码错误!");
        }
        return "manage_pages/login";
    }

    /**
     * @description 优惠券管理
     * @author jose
     * @date 2020/6/22 8:19
     * @params [commodity]
     * @return java.lang.String
     */
    @RequestMapping("/toCouponManage")
    public String toCoupon(){
        return "manage_pages/couponManage";
    }

    @RequestMapping("/CouponManage")
    @ResponseBody
    public Map CouponManage(Integer page,Integer limit){
        if(page==null){
            page=1;
        }
        if(limit==null){
            limit=10;
        }
        int offset = (page-1)*limit;
        List<Coupon> list = couponService.queryAllByLimit(offset,limit);
        int count = couponService.couponCount();
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg","提示");
        map.put("code","0");
        map.put("data",list);
        map.put("count",count);
        return map;
    }

    //积分商品添加
    @RequestMapping("/addCoupon")
    @ResponseBody
    public String addCoupon(Coupon coupon){
        couponService.insert(coupon);
        return "yes";
    }
    @RequestMapping("/editCoupon")
    @ResponseBody
    public String editCoupon(Coupon coupon){
        couponService.update(coupon);
        return "yes";
    }
    @RequestMapping("/delCoupon")
    @ResponseBody
    public String delCoupon(Integer id){
        couponService.deleteById(id);
        return "yes";
    }

    /**
     * @description 订单管理
     * @author jose
     * @date 2020/6/30 8:28
     * @params
     * @return
     */
    @RequestMapping("/toOrderManage")
    public String toOrderManage(){
        return "manage_pages/orderManage";
    }

    @RequestMapping("/OrderEdit")
    @ResponseBody
    public String OrderEdit(String logisticsCompany,Integer orderId){
        UserOrder userOrder = new UserOrder();
        userOrder.setOrderId(orderId);
        userOrder.setLogisticsCompany(logisticsCompany);
        userOrder.setOrderState(Constant.SHIPPED);
        userOrder.setDeliveryTime(new Date());
        if ("顺丰".equals(userOrder.getLogisticsCompany())) {
            userOrderService.editOrder(userOrder, 1);
        } else if ("韵达".equals(userOrder.getLogisticsCompany())) {
            userOrderService.editOrder(userOrder, 3);
        } else if ("中通".equals(userOrder.getLogisticsCompany())) {
            userOrderService.editOrder(userOrder, 3);
        } else if ("圆通".equals(userOrder.getLogisticsCompany())) {
            userOrderService.editOrder(userOrder, 3);
        } else if ("京东".equals(userOrder.getLogisticsCompany())) {
            userOrderService.editOrder(userOrder, 2);
        } else {
            return "no";
        }
        return "yes";
    }
    /**
     * @description 积分商城
     * @author jose
     * @date 2020/6/22 10:38
     * @params []
     * @return java.lang.String
     */
    @RequestMapping("/toGoods")
    public String toGoods(){
        return "manage_pages/goods";
    }

    //积分山品列表
    @RequestMapping("/goods")
    @ResponseBody
    public Map goods(Integer page,Integer limit) throws IOException {
         if(page==null){
            page=1;
        }
        if(limit==null){
            limit=10;
        }
        int offset = (page-1)*limit;
        List<Commodity> list = commodityService.queryAllByLimit(offset,limit);
        int count = commodityService.commodityCount();
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg","提示");
        map.put("code","0");
        map.put("data",list);
        map.put("count",count);
        return map;
    }


    //积分商品添加
    @RequestMapping("/addGoods")
    @ResponseBody
    public String addGoods(Commodity commodity){
        commodity.setReleaseTime(new Date());
        commodity.setGoodsSell(0);
        commodityService.insert(commodity);
        return "yes";
    }

    @RequestMapping("/editGoods")
    @ResponseBody
    public String editGoods(Commodity commodity){
        commodityService.update(commodity);
        return "yes";
    }
    @RequestMapping("/delGoods")
    @ResponseBody
    public String editGoods(Integer id){
        commodityService.deleteById(id);
        return "yes";
    }


    @RequestMapping("/debit")//借贷
    public String debit(Model model){
        model.addAttribute("dType",debitTypeService.queryAllList());
        return "debit/backstage/jdback";
    }

    @RequestMapping("/debitList")//借贷数据
    @ResponseBody
    public Map debitList(Integer page,Integer limit){
        int offset = (page-1)*limit;
        Map  map = new HashMap();
        map.put("code","0");
        map.put("msg","提示");
        map.put("count",zeroService.QueryCount());
        map.put("data",debitMarkService.AllDebit(offset,limit));
        return map;
    }

    //去新增借贷
    @RequestMapping("/toAddDebit")
    public String toAddDebit(Model model){
        //model.addAttribute("dType",debitTypeService.queryAll());
        return "debit/backstage/addMark";

    }

    //新增借贷
    @RequestMapping("/addDebit")
    public String addDebit(DebitMark debitMark){
        debitMark.setOnlineTime(new Date());//设置当前时间为上线时间
        debitMark.setYearInterset(debitMark.getYearInterset()/100);
        debitMarkService.insert(debitMark);
        return "redirect:/admin/debit";
    }

    //修改借贷
    @RequestMapping("/updDebit")
    public String updDebit(DebitMark debitMark){
        debitMark.setYearInterset(debitMark.getYearInterset()/100);
        debitMarkService.update(debitMark);
        return "redirect:/admin/debit";
    }

    //去修改借贷页面
    @RequestMapping("/updDebit/{mId}")
    public String toUpdDebit(@PathVariable int mId,Model model){
        DebitMark debitMark = debitMarkService.queryById(mId);
        model.addAttribute("debit",debitMark);
        //借贷类型
        model.addAttribute("dType",debitTypeService.queryAllList());
        return "debit/backstage/updMark";

    }

    //去修改借贷页面
    @RequestMapping("/delDebit/{mId}")
    public String toUpdDebit(@PathVariable int mId){
        debitMarkService.deleteById(mId);
        return "redirect:/admin/debit";
    }

    @RequestMapping("/audit")//借贷审核数据页面
    public String audit(Model model){
        model.addAttribute("dType",debitTypeService.queryAllList());
        return "debit/backstage/audit";
    }

    @RequestMapping("/audit/{lid}")//去审核借贷
    public String auditPage(@PathVariable int lid,Model model){
        Map audit = zeroService.LoanbyId(lid);
        model.addAttribute("aduit",audit);
         //紧急联系人
        model.addAttribute("clans",clanTabService.queryBylId(lid));
        Integer userid = (Integer) audit.get("user_id");
        //信用分
        model.addAttribute("user",userService.queryById(userid));
        return "debit/backstage/aduitPage";
    }

    @PostMapping("/updAduit")//审核借贷
    public String updAduit(LoanApplication loan){
        //拒绝通过
        if(loan.getOrderState()==Constant.LOAN_ORDER_STATE_NO_PASS){
            loan.setAuditTime(new Date());
        }
        //修改为已审核
        if(loan.getOrderState()== Constant.LOAN_ORDER_STATE_PASS){
            loan.setAuditTime(new Date());
            //算出每月还款金额
            float monthMoney =  (loan.getInterestRate()/100+1)*loan.getMaxMoney()/loan.getLMonth();
            loan.setMonthMoney(monthMoney);
        }
        //修改为已放款时
        if(loan.getOrderState()==Constant.LOAN_ORDER_STATE_LOAN_SUCCESS){
            loan.setLoanTime(new Date());//新增放款时间
            UserInfo userInfo = userInfoService.queryByuId(loan.getUserId());

            //新增用户余额
            userInfo.setMoney(loan.getMaxMoney()+userInfo.getMoney());
            userInfoService.update(userInfo);

            //新增用户资金记录
            Fund fund = new Fund();
            fund.setFundPost(MoneyFund.FUND_BORROW_MONEY);//借款通过
            fund.setFundAmunt(Float.valueOf(loan.getMaxMoney()));
            fund.setUId(loan.getUserId());
            fundService.insert(fund);


            //变成散标
            looseBidService.toLooseBid(loanApplicationService.queryById(loan.getLId()));
            //记录还款时间
            for (int i = 1; i <=loan.getLMonth() ; i++) {
                redisUtil.set("loan:"+loan.getLId()+","+i,"",60*60*24*30*i+ Utill.TodaySeconds());
            }
        }
        loanApplicationService.update(loan);
        return "redirect:/admin/audit";
    }



    @RequestMapping("/auditList")//借贷审核数据
    @ResponseBody
    public Map auditList (Integer page,Integer limit){
        if(page==null){
            page=1;
        }
        if(limit == null){
            limit = 10;
        }
        int offset = (page-1)*limit;
        Map  map = new HashMap();
        map.put("code","0");
        map.put("msg","提示");
        map.put("count",zeroService.QueryCount());
        map.put("data",zeroService.AllLoan(offset,limit));
        return map;
    }

    @RequestMapping("/audit/seek")//借贷审核数据
    @ResponseBody
    public Map seek (Integer page,Integer limit,String status,String month,String yearInterset,String order_state,String username){
        if(limit == null){
            limit = 10;
        }
        if(page==null){
            page=1;
        }
        int offset = (page-1)*limit;
        Map conditionMap = new HashMap();
        conditionMap.put("offset",offset);
        conditionMap.put("limit",limit);
        conditionMap.put("status",status);
        conditionMap.put("month",month);
        conditionMap.put("yearInterset",yearInterset);
        conditionMap.put("orderState",order_state);
        conditionMap.put("username",username);
        Map  map = new HashMap();
        map.put("code","0");
        map.put("msg","提示");
        map.put("count",1);
        map.put("data",zeroService.LoanCondition(conditionMap));
        return map;
    }

    //利率管理
    @RequestMapping("/interset")
    public String interset(){
        return "debit/backstage/interset";
    }

    //利率管理
    @RequestMapping("/intersetList")
    @ResponseBody
    public Map intersetList(){
        List<DebitType> debitTypes = debitTypeService.queryAllList();
        Map  map = new HashMap();
        map.put("code","0");
        map.put("msg","提示");
        map.put("count",debitTypes.size());
        map.put("data",debitTypes);
        return map;
    }

    //利率修改页面
    @GetMapping("/interset/{tid}")
    public String tointerset(@PathVariable int tid,Model model){
        model.addAttribute("intset",debitTypeService.queryById(tid));
        return "debit/backstage/updInterset";
    }

    //利率修改
    @PostMapping("/updinterset")
    public String updinterset(DebitType debitType){
        debitTypeService.update(debitType);
        return "redirect:/admin/interset";
    }

    /**
     * @description 公告添加
     * @author jose
     * @date 2020/6/11 14:55
     * @params [notice]
     * @return java.lang.String
     */
    @RequestMapping("/addNotice")
    @ResponseBody
    public String addNotice(Notice notice){
        if(notice.getImg() == ""){
            notice.setImg(null);
        }
        if(notice.getContent() == "" && notice.getContent() == null){
            return "no";
        }
        if(notice.getTitle() == "" && notice.getTitle() == null){
            return "no";
        }
        notice.setReleaseTime(new Date());
        noticeService.insert(notice);
        return "ok";
    }

    /**
     * @description 删除公告
     * @author jose
     * @date 2020/6/17 10:34
     * @params [id]
     * @return java.lang.String
     */
    @RequestMapping("/delNotice")
    public String delNotice(@RequestParam("id") Integer id){
        noticeService.deleteById(id);
        return "redirect:/admin/advert";
    }

    /**
     * @description 查看公告
     * @author jose
     * @date 2020/6/17 10:34
     * @params [id, model]
     * @return java.lang.String
     */
    @RequestMapping("/selNotice/{id}")
    public String selNotice(@PathVariable("id") Integer id, Model model){
        model.addAttribute("xinxi",noticeService.queryById(id));
        return "pages/Exhibition";
    }

    /** 文件上传 */
    @RequestMapping(value = "/uploadImg")
    @ResponseBody
    public Map<String,Object> updatePersonal(@RequestParam(required=false) MultipartFile file,Integer type) throws IllegalStateException, IOException, IOException {
        if (!file.isEmpty()) {
            //上传文件路径
            String path = null;
            String topPath = null;
            if(type == 1){
                path = "D:\\Temp\\imgs\\goods";
                topPath = "goods/";
            }else if(type == 2) {
                path = "D:\\Temp\\imgs";
                topPath = "imgs/";

            }

            //上传文件名
            String filename = file.getOriginalFilename();
            File filepath = new File(path, filename);

            //判断路径是否存在，没有就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }

            //将上传文件保存到一个目标文档中
            File file1 = new File(path + File.separator + filename);
            file.transferTo(file1);
            Map<String,Object> res = new HashMap<>();
            //返回的是一个url对象
            res.put("url", topPath+filename);
            return res;

        } else {
            Map map = new HashMap();
            map.put("code","\"code\": 1");
            return map;
        }
    }
}
